"""
更新各平台MongoDB热点数据的时间戳
"""
import os
from datetime import datetime, timedelta
from pymongo import MongoClient


def update_collection_timestamps(collection, platform_name):
    """更新单个集合的时间戳"""
    now = datetime.now()
    updated_count = 0

    # 获取所有数据并按rank排序
    items = list(collection.find({}).sort('rank', 1))

    for idx, item in enumerate(items):
        rank = item.get('rank', idx + 1)

        # 排名越靠前，时间越新
        # 为每条记录添加微小的时间差异，避免唯一索引冲突
        if rank <= 10:
            time_delta = timedelta(minutes=0, seconds=idx)  # 当前时间 + 序号秒
        elif rank <= 30:
            time_delta = timedelta(minutes=30, seconds=idx)  # 30分钟前 + 序号秒
        elif rank <= 50:
            time_delta = timedelta(hours=1, seconds=idx)  # 1小时前 + 序号秒
        else:
            time_delta = timedelta(hours=2, seconds=idx)  # 2小时前 + 序号秒

        new_time = now - time_delta

        # 更新 crawled_at 和 updated_at 字段
        # 通过添加秒级差异(seconds=idx)避免唯一索引冲突
        collection.update_one(
            {'_id': item['_id']},
            {
                '$set': {
                    'crawled_at': new_time,
                    'updated_at': new_time
                }
            }
        )
        updated_count += 1

    return updated_count


def main():
    print("=" * 70)
    print("MongoDB平台热点数据时间戳更新工具")
    print("=" * 70)

    # 连接MongoDB
    mongo_uri = os.getenv('MONGODB_URI', 'mongodb://admin:newhand@localhost:27017/')
    client = MongoClient(mongo_uri)
    db = client['crawler_db']

    # 平台集合列表
    platform_collections = [
        'weibo_hot_items',
        'zhihu_hot_items',
        'baidu_hot_items',
        'douyin_hot_items',
        'bilibili_hot_items',
        'toutiao_hot_items',
        'weixin_hot_items',
        'xiaohongshu_hot_items',
        'twitter_hot_items',
        'reddit_hot_items',
        'youtube_hot_items'
    ]

    print("\n正在更新各平台数据...\n")
    print("=" * 70)

    total_updated = 0

    for coll_name in platform_collections:
        collection = db[coll_name]
        count = collection.count_documents({})

        if count > 0:
            print(f"📊 {coll_name:30} {count:4} 条 -> ", end='')
            updated = update_collection_timestamps(collection, coll_name)
            total_updated += updated
            print(f"✅ 已更新 {updated} 条")

            # 显示更新后的第一条数据
            sample = collection.find_one({}, sort=[('rank', 1)])
            if sample:
                print(f"   └─ 示例: {sample.get('title', 'N/A')[:40]}")
                print(f"      时间: {sample.get('crawled_at', 'N/A')}")
        else:
            print(f"⚠️  {coll_name:30} {count:4} 条 -> 跳过（无数据）")

    print("=" * 70)
    print(f"\n✅ 完成！共更新 {total_updated} 条数据")
    print("\n💡 现在前端应该可以看到最新的热点数据了！")
    print("   刷新热点雷达页面即可查看")
    print("=" * 70)

    client.close()


if __name__ == '__main__':
    main()
